package com.ssy.lingxi.order.serviceimpl.feign;

import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.product.PriceTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.api.feign.ActivityGoodsControllerFeign;
import com.ssy.lingxi.marketing.api.feign.CouponControllerFeign;
import com.ssy.lingxi.marketing.api.model.constant.ActivityRecordTypeEnum;
import com.ssy.lingxi.marketing.api.model.request.*;
import com.ssy.lingxi.marketing.api.model.response.CartActivityPriceBaseResponse;
import com.ssy.lingxi.marketing.api.model.response.CartActivityPriceFeignResponse;
import com.ssy.lingxi.marketing.api.model.response.CartOrderResp;
import com.ssy.lingxi.order.model.bo.VendorBO;
import com.ssy.lingxi.order.model.constant.OrderPromotionTypeEnum;
import com.ssy.lingxi.order.model.dto.*;
import com.ssy.lingxi.order.model.vo.basic.request.MobileOrderProductVO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderCouponVO;
import com.ssy.lingxi.order.repository.OrderGiveCouponRepository;
import com.ssy.lingxi.order.service.feign.IMarketingFeignService;
import com.ssy.lingxi.order.utils.NumberUtil;
import com.ssy.lingxi.order.utils.OrderDateTimeUtil;
import com.ssy.lingxi.order.utils.OrderStringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 营销活动Feign接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-10-27
 */
@Service
public class MarketingFeignServiceImpl implements IMarketingFeignService {
    private static final Logger logger = LoggerFactory.getLogger(MarketingFeignServiceImpl.class);

    @Resource
    private ActivityGoodsControllerFeign activityGoodsControllerFeign;

    @Resource
    private CouponControllerFeign couponControllerFeign;

    @Resource
    private OrderGiveCouponRepository orderGiveCouponRepository;

    /**
     * 查询订单促销活动、优惠券、商品到手价（含赠品，套餐，订单商品参与的活动列表）
     *
     * @param shopId          订单来源商城Id
     * @param buyerMemberId   采购会员Id
     * @param buyerRoleId     采购会员角色Id
     * @param buyerMemberLevelType 当前用户（采购会员）等级类型
     * @param products        商品信息列表（改变并返回）
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PromotionProductDTO>> findOrderPromotions(Long shopId, Long buyerMemberId, Long buyerRoleId, Integer buyerMemberLevelType, List<OrderProductDetailDTO> products) {
        if(CollectionUtils.isEmpty(products)) {
            return Wrapper.success(new ArrayList<>());
        }

        //Step 1: 调用营销服务接口，查询普通商品，套餐主商品，换购的商品、被换购的商品、其他营销活动商品（不查询套餐中的商品、赠品）
        List<CartActivityPriceRequest> priceRequests = products.stream().filter(p -> !p.getPriceType().equals(PriceTypeEnum.Gift.getCode()) && !p.getPromotionType().equals(OrderPromotionTypeEnum.PART_OF_SET.getCode())).map(p -> {
            CartActivityPriceRequest priceRequest = new CartActivityPriceRequest();
            priceRequest.setUpperMemberId(p.getVendorMemberId());
            priceRequest.setUpperRoleId(p.getVendorRoleId());
            priceRequest.setShopId(shopId);
            priceRequest.setProductId(p.getProductId());
            priceRequest.setSkuId(p.getSkuId());
            priceRequest.setCommodityType(buyerMemberLevelType.equals(MemberLevelTypeEnum.MERCHANT.getCode()) ? 1 : 2);
            if(p.getPromotionType().equals(OrderPromotionTypeEnum.EXCHANGED.getCode())) {
                priceRequest.setParentSkuId(p.getParentSkuId());
            }

            if(p.getPromotionType().equals(OrderPromotionTypeEnum.PRIMARY_OF_SET.getCode())) {
                priceRequest.setGroupNo(p.getGroupNo());
            }

            priceRequest.setQuantity(p.getQuantity().doubleValue());
            priceRequest.setJoinGroup(false);
            return priceRequest;
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(priceRequests)) {
            return Wrapper.success(new ArrayList<>());
        }

        CartActivityPriceFeignRequest request = new CartActivityPriceFeignRequest();
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setSkuList(priceRequests);

        Wrapper<List<CartActivityPriceFeignResponse>> promotionResult = activityGoodsControllerFeign.getPreferentialPrice(request);
        logger.info("创建订单调用营销服务入参:{}",request);
        if(promotionResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(promotionResult.getCode(), promotionResult.getMessage());
        }

        //先处理换购主商品
        List<Long> parentSkuIds = promotionResult.getData().stream().filter(r -> NumberUtil.notNullAndPositive(r.getParentSkuId())).map(CartActivityPriceBaseResponse::getParentSkuId).collect(Collectors.toList());
        List<PromotionProductDTO> promotionProducts = promotionResult.getData().stream().map(r -> {
            PromotionProductDTO p = new PromotionProductDTO();
            if(parentSkuIds.contains(r.getSkuId())) {
                p.setPromotionType(OrderPromotionTypeEnum.PRIMARY_OF_SET.getCode());
            } else if(NumberUtil.notNullAndPositive(r.getParentSkuId())) {
                p.setPromotionType(OrderPromotionTypeEnum.EXCHANGED.getCode());
            } else if(NumberUtil.notNullAndPositive(r.getGroupNo())) {
                p.setPromotionType(OrderPromotionTypeEnum.PRIMARY_OF_SET.getCode());
            }

            p.setProductId(r.getProductId());
            p.setSkuId(r.getSkuId());
            p.setParentSkuId(r.getParentSkuId() == null ? 0L : r.getParentSkuId());
            p.setGroupNo(r.getGroupNo() == null ? 0 : r.getGroupNo());
            p.setQuantity(r.getQuantity() == null ? BigDecimal.ZERO : BigDecimal.valueOf(r.getQuantity()).setScale(3, RoundingMode.HALF_UP));

            //被换购的商品没有会员折扣
            if(p.getPromotionType().equals(OrderPromotionTypeEnum.EXCHANGED.getCode())) {
                p.setDiscount(BigDecimal.ONE);
            } else {
                p.setDiscount(r.getParameter() == null ? BigDecimal.ONE : BigDecimal.valueOf(r.getParameter()));
            }

            p.setPrice(BigDecimal.valueOf(r.getGoodsPrice()).setScale(3, RoundingMode.HALF_UP));
            //营销服务返回的价格优先级 groupHandPrice -> handPrice -> basePrice -> goodsPrice
            p.setRefPrice(BigDecimal.valueOf(Optional.ofNullable(r.getGroupHandPrice()).orElse(Optional.ofNullable(r.getHandPrice()).orElse(Optional.ofNullable(r.getBasePrice()).orElse(Optional.ofNullable(r.getGoodsPrice()).orElse(0D))))).setScale(3, RoundingMode.HALF_UP));
            //单个商品通过营销活动减少的金额
            p.setPromotionAmount(NumberUtil.isNullOrNegative(r.getSaleTotalAmount()) ? BigDecimal.ZERO : BigDecimal.valueOf(r.getSaleTotalAmount()));

            //赠品
            p.setGifts(CollectionUtils.isEmpty(r.getGiveList()) ? new ArrayList<>() : r.getGiveList().stream().filter(g -> g.getGiftType().equals(1)).map(g -> {
                SubProductDTO subProduct = new SubProductDTO();
                subProduct.setProductId(g.getProductId());
                subProduct.setSkuId(g.getId());
                //赠品的单价从商品服务查询
                subProduct.setPrice(BigDecimal.ZERO);
                subProduct.setRefPrice(BigDecimal.ZERO);
                subProduct.setName(g.getName());
                subProduct.setQuantity(g.getNum() == null ? BigDecimal.ONE : g.getNum());
                subProduct.setCategory(g.getCategory());
                subProduct.setBrand(g.getBrand());
                subProduct.setUnit(g.getUnit());
                return subProduct;
            }).collect(Collectors.toList()));

            //赠优惠卷
            p.setGiveCouponDTOList(CollectionUtils.isEmpty(r.getGiveList()) ? new ArrayList<>() : r.getGiveList().stream().filter(g -> g.getGiftType().equals(2)).map(g -> {
                OrderGiveCouponDTO orderGiveCouponDTO = new OrderGiveCouponDTO();
                orderGiveCouponDTO.setProductId(g.getProductId());
                orderGiveCouponDTO.setSkuId(r.getSkuId());
                orderGiveCouponDTO.setGiveId(g.getId());
                //赠品的单价从商品服务查询
                orderGiveCouponDTO.setName(g.getName());
                orderGiveCouponDTO.setQuantity(g.getNum() == null ? BigDecimal.ONE : g.getNum());
                orderGiveCouponDTO.setCategory(g.getCategory());
                orderGiveCouponDTO.setBrand(g.getBrand());
                orderGiveCouponDTO.setUnit(g.getUnit());
                return orderGiveCouponDTO;
            }).collect(Collectors.toList()));

            //套餐商品
            p.setSubProducts(CollectionUtils.isEmpty(r.getSetMealList()) ? new ArrayList<>() : r.getSetMealList().stream().map(s -> {
                SubProductDTO subProduct = new SubProductDTO();
                subProduct.setProductId(s.getProductId());
                subProduct.setSkuId(s.getId());
                subProduct.setPrice(s.getPrice() == null ? BigDecimal.ZERO : s.getPrice());
                subProduct.setRefPrice(s.getHandPrice() == null ? BigDecimal.ZERO : s.getHandPrice());
                subProduct.setName(s.getName());
                subProduct.setQuantity(s.getNum() == null ? BigDecimal.ONE : s.getNum());
                subProduct.setCategory(s.getCategory());
                subProduct.setBrand(s.getBrand());
                subProduct.setUnit(s.getUnit());
                return subProduct;
            }).collect(Collectors.toList()));

            //营销活动
            p.setPromotions(CollectionUtils.isEmpty(r.getActivityList()) ? new ArrayList<>() : r.getActivityList().stream().map(act -> {
                PromotionDTO promotion = new PromotionDTO();
                promotion.setPromotionId(act.getActivityId());
                promotion.setName(act.getActivityName());
                promotion.setPromotionType(act.getActivityType());
                promotion.setBelongType(act.getBelongType());
                promotion.setStartTime(OrderDateTimeUtil.timestampToLocalDateTime(act.getStartTime()));
                promotion.setExpireTime(OrderDateTimeUtil.timestampToLocalDateTime(act.getEndTime()));
                return promotion;
            }).collect(Collectors.toList()));

            logger.info("赠送优惠券信息:{}",p.getGiveCouponDTOList());
            logger.info("赠送全部优惠券信息:{}",r.getGiveList());
            return p;
        }).collect(Collectors.toList());

        return Wrapper.success(promotionProducts);
    }

    /**
     * 查询订单促销活动、优惠券、商品到手价（含赠品，套餐，订单商品参与的活动列表）
     *
     * @param shopId               订单来源商城Id
     * @param buyerMemberId        采购会员Id
     * @param buyerRoleId          采购会员角色Id
     * @param buyerMemberLevelType 当前用户（采购会员）等级类型
     * @param products             订单商品信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PromotionProductDTO>> findGroupOrderPromotions(Long shopId, Long buyerMemberId, Long buyerRoleId, Integer buyerMemberLevelType, List<MobileOrderProductVO> products) {
        //Step 1: 调用营销服务接口，查询其他营销活动商品，不查询普通商品，套餐主商品，换购的商品、被换购的商品、套餐中的商品、赠品
        List<CartActivityPriceRequest> priceRequests = products.stream().map(p -> {
            CartActivityPriceRequest priceRequest = new CartActivityPriceRequest();
            priceRequest.setUpperMemberId(p.getVendorMemberId());
            priceRequest.setUpperRoleId(p.getVendorRoleId());
            priceRequest.setShopId(shopId);
            priceRequest.setProductId(p.getProductId());
            priceRequest.setSkuId(p.getSkuId());
            priceRequest.setCommodityType(buyerMemberLevelType.equals(MemberLevelTypeEnum.MERCHANT.getCode()) ? 1 : 2);
            priceRequest.setQuantity(p.getQuantity().doubleValue());
            priceRequest.setJoinGroup(true);
            return priceRequest;
        }).collect(Collectors.toList());

        CartActivityPriceFeignRequest request = new CartActivityPriceFeignRequest();
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setSkuList(priceRequests);

        Wrapper<List<CartActivityPriceFeignResponse>> promotionResult = activityGoodsControllerFeign.getPreferentialPrice(request);
        if(promotionResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(promotionResult.getCode(), promotionResult.getMessage());
        }

        List<PromotionProductDTO> promotionProducts = promotionResult.getData().stream().map(r -> {
            PromotionProductDTO p = new PromotionProductDTO();
            p.setPromotionType(OrderPromotionTypeEnum.OTHER_PROMOTION_PRODUCT.getCode());
            p.setProductId(r.getProductId());
            p.setSkuId(r.getSkuId());
            p.setParentSkuId(r.getParentSkuId() == null ? 0L : r.getParentSkuId());
            p.setGroupNo(r.getGroupNo() == null ? 0 : r.getGroupNo());
            p.setQuantity(r.getQuantity() == null ? BigDecimal.ZERO : BigDecimal.valueOf(r.getQuantity()).setScale(3, RoundingMode.HALF_UP));
            p.setDiscount(r.getParameter() == null ? BigDecimal.ONE : BigDecimal.valueOf(r.getParameter()));
            p.setPrice(BigDecimal.valueOf(r.getGoodsPrice()).setScale(3, RoundingMode.HALF_UP));
            p.setRefPrice(r.getGroupHandPrice() == null ? (r.getHandPrice() == null ? BigDecimal.valueOf(r.getBasePrice()).setScale(3, RoundingMode.HALF_UP) : BigDecimal.valueOf(r.getHandPrice()).setScale(3, RoundingMode.HALF_UP)) : BigDecimal.valueOf(r.getGroupHandPrice()).setScale(3, RoundingMode.HALF_UP));
            //单个商品通过营销活动减少的金额
            p.setPromotionAmount(NumberUtil.isNullOrNegative(r.getSaleTotalAmount()) ? BigDecimal.ZERO : BigDecimal.valueOf(r.getSaleTotalAmount()));

            //赠品
            p.setGifts(new ArrayList<>());

            //套餐商品
            p.setSubProducts(new ArrayList<>());

            //营销活动
            p.setPromotions(CollectionUtils.isEmpty(r.getActivityList()) ? new ArrayList<>() : r.getActivityList().stream().map(act -> {
                PromotionDTO promotion = new PromotionDTO();
                promotion.setPromotionId(act.getActivityId());
                promotion.setName(act.getActivityName());
                promotion.setPromotionType(act.getActivityType());
                promotion.setBelongType(act.getBelongType());
                promotion.setStartTime(OrderDateTimeUtil.timestampToLocalDateTime(act.getStartTime()));
                promotion.setExpireTime(OrderDateTimeUtil.timestampToLocalDateTime(act.getEndTime()));
                return promotion;
            }).collect(Collectors.toList()));

            return p;
        }).collect(Collectors.toList());

        return Wrapper.success(promotionProducts);
    }

    /**
     * 查询优惠券列表
     *
     * @param shopId       订单来源商城Id
     * @param buyerMemberId 采购会员Id
     * @param buyerRoleId   采购会员角色Id
     * @param orderCoupons    接口参数中的优惠券列表
     * @param orderProducts   订单商品列表
     * @param promotionAmount 根据营销活动到手价计算后的商品总价
     * @return 优惠券列表
     */
    @Override
    public Wrapper<List<OrderCouponDetailDTO>> findOrderCoupons(Long shopId, Long buyerMemberId, Long buyerRoleId, List<OrderCouponVO> orderCoupons, List<OrderProductDetailDTO> orderProducts, BigDecimal promotionAmount) {
        if(CollectionUtils.isEmpty(orderCoupons)) {
            return Wrapper.success(new ArrayList<>());
        }

        CartOrderReq request = new CartOrderReq();
        request.setShopId(shopId);
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setOrderAmount(promotionAmount);
        request.setCouponAvailableReqList(orderCoupons.stream().map(c -> {
            CouponAvailableReq req = new CouponAvailableReq();
            req.setCouponDetailId(c.getCouponId());
            req.setBelongType(c.getBelongType());
            return req;
        }).collect(Collectors.toList()));

        Map<VendorBO, List<OrderProductDetailDTO>> map = orderProducts.stream().collect(Collectors.groupingBy(p -> new VendorBO(p.getVendorMemberId(), p.getVendorRoleId())));
        request.setCartVendorReqList(map.entrySet().stream().map(entry -> {
            CartVendorReq req = new CartVendorReq();
            req.setVendorMemberId(entry.getKey().getVendorMemberId());
            req.setVendorRoleId(entry.getKey().getVendorRoleId());
            req.setSkuIdList(entry.getValue().stream().map(OrderProductDetailDTO::getSkuId).collect(Collectors.toList()));
            return req;
        }).collect(Collectors.toList()));

        Wrapper<List<CartOrderResp>> result = couponControllerFeign.checkCouponAvailable(request);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        if(CollectionUtils.isEmpty(result.getData())) {
            return Wrapper.success(new ArrayList<>());
        }

        return Wrapper.success(result.getData().stream().map(r -> {
            OrderCouponDetailDTO c = new OrderCouponDetailDTO();
            c.setVendorMemberId(NumberUtil.notNullAndPositive(r.getVendorMemberId()) ? r.getVendorMemberId() : 0L);
            c.setVendorRoleId(NumberUtil.notNullAndPositive(r.getVendorRoleId()) ? r.getVendorRoleId() : 0L);
            c.setCouponId(r.getCouponDetailId());
            c.setName(r.getName());
            c.setCouponType(r.getCouponType());
            c.setBelongType(r.getBelongType());
            c.setSkuIds(CollectionUtils.isEmpty(r.getSuitableSkuIdList()) ? new ArrayList<>() : r.getSuitableSkuIdList());
            c.setAmount(NumberUtil.isNullOrNegativeZero(r.getDenomination()) ? BigDecimal.ZERO : r.getDenomination().setScale(3, RoundingMode.HALF_UP));
            c.setAvailable(NumberUtil.notNullOrZero(r.getCanUse()) && (r.getCanUse().equals(1)));
            c.setStartTime(OrderDateTimeUtil.timestampToLocalDateTime(r.getValidTimeStart()));
            c.setExpireTime(OrderDateTimeUtil.timestampToLocalDateTime(r.getValidTimeEnd()));
            return c;
        }).collect(Collectors.toList()));
    }

    /**
     * 订单创建完成后、取消订单时，修改营销活动记录
     *
     * @param orderId           订单Id
     * @param createTime        订单创建时间
     * @param buyerMemberId     采购会员Id
     * @param buyerRoleId       采购会员角色Id
     * @param buyerMemberName   采购会员名称
     * @param shopId            订单来源商城Id
     * @param shopName          订单来源商城名称
     * @param promotionProducts 商品及营销活动列表
     */
    @Async
    @Override
    public void updateOrderPromotions(Long orderId, LocalDateTime createTime, Long buyerMemberId, Long buyerRoleId, String buyerMemberName, Long shopId, String shopName, List<PromotionNotifyDTO> promotionProducts) {
        List<GoodsSalesItemReq> items = promotionProducts.stream().map(p -> {
            GoodsSalesItemReq item = new GoodsSalesItemReq();
            item.setOrderId(orderId);
            item.setSkuId(p.getSkuId());
            item.setAmount(p.getRefPrice().multiply(p.getQuantity()).doubleValue());
            item.setNum(p.getQuantity().doubleValue());
            item.setOrderNo(p.getOrderNo());
            item.setActivityList(p.getPromotions().stream().map(promotion -> {
                GoodsSalesItemActivityReq req = new GoodsSalesItemActivityReq();
                req.setActivityId(promotion.getPromotionId());
                req.setBelongType(promotion.getBelongType());
                return req;
            }).collect(Collectors.toList()));
            return item;
        }).filter(item -> !CollectionUtils.isEmpty(item.getActivityList())).collect(Collectors.toList());

        GoodsSalesReq request = new GoodsSalesReq();
        request.setOrderTime(OrderDateTimeUtil.localDateTimeToTimestamp(createTime));
        request.setRecordType(ActivityRecordTypeEnum.ORDER.getCode());
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setMemberName(buyerMemberName);
        request.setShopId(shopId);
        request.setShopName(shopName);
        request.setItemList(items);

        try {
            logger.info("营销服务扣减、返还活动记录参数 => " + OrderStringUtil.serializeObject(request));
            Wrapper<?> result = activityGoodsControllerFeign.updateGoodsSales(request);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                logger.error("调用营销服务扣减、返还活动记录错误, code:" + result.getCode() + ", msg:" + result.getMessage());
            }
        } catch (Exception e) {
            logger.error("调用营销服务扣减、返还活动记录异常, msg:" + e.getMessage());
        }
    }

    /**
     * 订单创建完成后，消耗优惠券
     *
     * @param shopId      订单来源商城Id
     * @param shopName    订单来源商城名称
     * @param orderId     订单Id
     * @param orderNo     订单编号
     * @param createTime  订单创建时间
     * @param totalAmount 订单金额
     * @param coupons     优惠券列表
     */
    @Async
    @Override
    public void spendCoupons(Long shopId, String shopName, Long orderId, String orderNo, Long buyerMemberId, Long buyerRoleId, String buyerMemberName, LocalDateTime createTime, BigDecimal totalAmount, List<OrderCouponDetailDTO> coupons) {
        CouponConsumeReq request = new CouponConsumeReq();
        request.setShopId(shopId);
        request.setShopName(shopName);
        request.setOrderId(orderId);
        request.setOrderNo(orderNo);
        request.setOrderCreateTime(OrderDateTimeUtil.localDateTimeToTimestamp(createTime));
        request.setTotalAmount(totalAmount);
        request.setBuyerMemberId(buyerMemberId);
        request.setBuyerRoleId(buyerRoleId);
        request.setBuyerMemberName(buyerMemberName);
        request.setCouponDetailList(coupons.stream().map(coupon ->{
            CouponDetailConsumeReq req = new CouponDetailConsumeReq();
            req.setCouponDetailId(coupon.getCouponId());
            req.setBelongType(coupon.getBelongType());
            return req;
        }).collect(Collectors.toList()));

        try {
            Wrapper<Void> result = couponControllerFeign.consumeCoupon(request);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                logger.error("订单创建完成后，消耗优惠券错误, code:" + result.getCode() + ", msg:" + result.getMessage());
            }

        } catch (Exception e) {
            logger.error("订单创建完成后，消耗优惠券异常, msg: " + e.getMessage());
        }
    }

    /**
     * 取消订单后，返还优惠券
     *
     * @param coupons 优惠券列表
     */
    @Async
    @Override
    public void resumeCoupons(List<OrderCouponDetailDTO> coupons) {
        List<CouponDetailConsumeReq> request = coupons.stream().map(coupon -> {
            CouponDetailConsumeReq req = new CouponDetailConsumeReq();
            req.setCouponDetailId(coupon.getCouponId());
            req.setBelongType(coupon.getBelongType());
            return req;
        }).collect(Collectors.toList());

        try {
            Wrapper<Void> result = couponControllerFeign.returnCoupon(request);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                logger.error("订单取消后，返回优惠券错误, code:" + result.getCode() + ", msg:" + result.getMessage());
            }
        } catch (Exception e) {
            logger.error("订单取消后，返回优惠券异常, msg: " + e.getMessage());
        }
    }

    /**
     * 当拼团订单处于“待发货”状态时，通知营销服务，记录拼团订单
     *
     * @param orderId         订单Id
     * @param orderNo         订单号
     * @param buyerMemberId   采购会员Id
     * @param buyerRoleId     采购会员角色Id
     * @param buyerMemberName 采购会员名称
     * @param buyerMemberLogo 采购会员Logo
     * @param productId       拼团商品Id
     * @param skuId           拼团商品SkuId
     * @param quantity        拼团商品数量
     * @param promotionId     拼团活动Id
     * @param recordId        拼团活动记录Id
     * @param belongType      活动归属类型
     */
    @Override
    public Wrapper<Long> notifyGroupOrder(Long orderId, String orderNo, Long buyerMemberId, Long buyerRoleId, String buyerMemberName, String buyerMemberLogo, Long productId, Long skuId, BigDecimal quantity, Long promotionId, Long recordId, Integer belongType) {
        GroupPurchaseAddRequest request = new GroupPurchaseAddRequest();
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setMemberName(buyerMemberName);
        request.setLogo(buyerMemberLogo);
        request.setId(NumberUtil.isNullOrZero(recordId) ? null : recordId);
        request.setOrderId(orderId);
        request.setOrderNo(orderNo);
        request.setProductId(productId);
        request.setSkuId(skuId);
        request.setQuantity(quantity);
        request.setActivityId(promotionId);
        request.setBelongType(belongType);
        try {
            Wrapper<Long> result = activityGoodsControllerFeign.addGroupPurchase(request);
            logger.info("发送拼团消息 => " + OrderStringUtil.serializeObject(request) + " 返回结果：" + result.getCode() + ", 拼团Id：" + result.getData());
            return result;
        } catch (BusinessException e) {
            logger.info("发送拼团消息异常, code:" + e.getCode() + " , msg:" + e.getMsg());
            return Wrapper.fail(ResponseCode.SERVICE_ERROR);
        }
    }

    /**
     * 校验采购会员是否能参与拼团（自建的拼团）
     *
     * @param buyerMemberId 采购会员Id
     * @param buyerRoleId   采购会员角色Id
     * @param groupId       拼团Id
     * @return 查询结果
     */
    @Override
    public Wrapper<Boolean> checkGroupOrder(Long buyerMemberId, Long buyerRoleId, Long groupId) {
        GroupPurchaseCheckRequest request = new GroupPurchaseCheckRequest();
        request.setMemberId(buyerMemberId);
        request.setRoleId(buyerRoleId);
        request.setId(groupId);

        try {
            return activityGoodsControllerFeign.isRepeatJoinGroupPurchase(request);
        } catch (Exception ignored) {
            return Wrapper.fail(ResponseCode.SERVICE_MARKETING_ERROR);
        }
    }
}
